package com.hry.store.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hry.store.common.BuyerCart;
import com.hry.store.common.Const;
import com.hry.store.common.ServerResponse;
import com.hry.store.pojo.CartItem;
import com.hry.store.pojo.User;
import com.hry.store.service.CartService;
import com.hry.store.service.ProductColorService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private ProductColorService productColorService;


    /**
     * 添加商品到购物车
     */
    @RequestMapping("addItem")
    public String addCart(HttpSession session, HttpServletResponse response, HttpServletRequest request,
                          @RequestParam("secondCategoryId") Integer productId, @RequestParam("productPrice") BigDecimal productPrice,
                          @RequestParam("versionId") Integer versionId, @RequestParam("colorName") String colorName,
                          @RequestParam("productName") String productName, @RequestParam(value = "quantity", defaultValue = "1") Integer quantity, ModelMap modelMap) {
        ObjectMapper om = new ObjectMapper();
        om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        BuyerCart buyerCart = null;
        // 获取cookie中购物车
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (Const.BUYER_CART.equals(cookie.getName())) {
                    // 购物车对象与json互相转换
                    try {
                        buyerCart = om.readValue(URLDecoder.decode(cookie.getValue(), "utf-8"), BuyerCart.class);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        // cookie 中没有购物车， 创建购物车
        if (null == buyerCart) {
            buyerCart = new BuyerCart();
        }
        // 将当前商品追加到购物车
        if (null != productId && null != productPrice && null != colorName && null != versionId && null != quantity) {
            CartItem item = new CartItem();
            item.setProductId(productId);
            item.setProductPrice(productPrice);
            item.setColorName(colorName);
            // 获取一张图片作为样品图
            List list = productColorService.getProductImgs(productId, versionId, colorName);
            String url = (String) list.get(list.size() - 1);
            item.setProductImg(url);
            item.setQuantity(quantity);
            item.setVersionId(versionId);
            item.setProductName(productName);
            item.setProductTotalPrice(productPrice);
            modelMap.put("item", item);
            buyerCart.addItem(item);

        }

        // 做用户是否登陆判断
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (null != user) {
            // 登录了 将商品追加到MySQL中
            int resultCount = cartService.addItemsByEmail(buyerCart, user.getUserEmail());
            if (resultCount > 0) {
                // 插入到购车车表成功
                // 清空cookie 设置活动时间为0 立马销毁
                Cookie cookie = new Cookie(Const.BUYER_CART, null);
                cookie.setPath("/");
                cookie.setMaxAge(-0);
                response.addCookie(cookie);
                return "addSuccess";
            }
        } else {
            // 未登录, 保存购物车到cookie中
            cartService.addItemToCookie(buyerCart, response);
            return "addSuccess";
        }
        return "error";
    }

    /**
     * 购物车面结算
     *
     * @param request
     * @param modelMap
     * @return
     */
    @RequestMapping("settleAccounts")
    public String pageCart(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws IOException {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        BuyerCart buyerCart = null;
        // 去cookie中读取购物车
        if (user == null) {
            ObjectMapper om = new ObjectMapper();
            om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            //从cookie中取数据
            Cookie[] cookies = request.getCookies();
            if (null != cookies && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    // 找到对应的cookie
                    if (Const.BUYER_CART.equals(cookie.getName())) {
                        try {
                            buyerCart = om.readValue(URLDecoder.decode(cookie.getValue(), "utf-8"), BuyerCart.class);
                            if (buyerCart.getItems().size() == 0) {
                                return "cart_error";
                            }
                            modelMap.put("buyerCart", buyerCart.getItems());
                            return "cart";
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } else {
            // 先检查cookie中是否存在数据
            ObjectMapper om = new ObjectMapper();
            om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            // 获取cookie中购物车
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (Const.BUYER_CART.equals(cookie.getName())) {
                        // 购物车对象与json互相转换
                        buyerCart = om.readValue(URLDecoder.decode(cookie.getValue(), "utf-8"), BuyerCart.class);
                    }
                }
            }
            if (buyerCart != null) {
                int resultCount = cartService.addItemsByEmail(buyerCart, user.getUserEmail());
                if (resultCount > 0) {
                    // 插入到购车车表成功
                    // 清空cookie 设置活动时间为0 立马销毁
                    Cookie cookie = new Cookie(Const.BUYER_CART, null);
                    cookie.setPath("/");
                    cookie.setMaxAge(-0);
                    response.addCookie(cookie);
                }
            } else {
                // 取数据库中读取购物车
                List buyerCarts = cartService.selectCartItemByEmail(user.getUserEmail());
                if (buyerCarts.size() != 0) {
                    modelMap.put("buyerCart", buyerCarts);
                    return "cart";
                } else {
                    return "cart_error";
                }
            }
        }
        return "cart_error";

    }

    /**
     * 从购物车中删除商品
     *
     * @return
     */
    @RequestMapping("deleteItem")
    @ResponseBody
    public ServerResponse deleteItem(HttpServletRequest request, HttpServletResponse response, @RequestParam("productId") Integer productId,
                                     @RequestParam("productName") String productName, @RequestParam("productPrice") BigDecimal productPrice,
                                     @RequestParam("versionId") Integer versionId, @RequestParam("colorName") String colorName) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (null != user) {
            // 从mysql中删除数据
            int count = cartService.deleteFromMysql(productId, productName, productPrice, versionId, colorName, user.getUserEmail());
            if (count > 0) {
                return ServerResponse.createBySuccess(Const.SUCCESS_CODE);
            }
        } else {
            // 用户没有登录，从cookie中删除数据
            ObjectMapper om = new ObjectMapper();
            om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            Cookie[] cookies = request.getCookies();
            BuyerCart buyerCart;
            Boolean result = null;
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Const.BUYER_CART)) {
                    try {
                        buyerCart = om.readValue(URLDecoder.decode(cookie.getValue(), "utf-8"), BuyerCart.class);
                        CartItem cartItem = new CartItem();
                        cartItem.setProductName(productName);
                        cartItem.setProductId(productId);
                        cartItem.setProductPrice(productPrice);
                        cartItem.setVersionId(versionId);
                        cartItem.setColorName(colorName);
                        buyerCart.removeItem(cartItem);
                        cartService.addItemToCookie(buyerCart, response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return ServerResponse.createBySuccess(Const.SUCCESS_CODE);
                }

            }
        }
        return ServerResponse.createByErrorMessage("error");

    }

    /**
     * 修改购物车中中的数量
     *
     * @return
     */

    @RequestMapping("editCartNumber")
    @ResponseBody
    public ServerResponse editCartNumber(HttpSession session, HttpServletResponse response, HttpServletRequest request,
                                         @RequestParam("productId") Integer productId, @RequestParam("productPrice") BigDecimal productPrice,
                                         @RequestParam("versionId") Integer versionId, @RequestParam("colorName") String colorName,
                                         @RequestParam("productName") String productName, @RequestParam("quantity") Integer quantity, ModelMap modelMap) throws IOException {
        // 做用户是否登陆判断
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            ObjectMapper om = new ObjectMapper();
            om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            BuyerCart buyerCart = null;
            // 获取cookie中购物车
            Cookie[] cookies = request.getCookies();
            if (cookies != null && cookies.length > 0) {
                for (Cookie cookie : cookies) {
                    if (Const.BUYER_CART.equals(cookie.getName())) {
                        // 购物车对象与json互相转换
                        buyerCart = om.readValue(URLDecoder.decode(cookie.getValue(), "utf-8"), BuyerCart.class);
                    }
                }
            }
            // 将当前商品追加到购物车
            if (null != productId && null != productPrice && null != colorName && null != versionId && null != quantity) {
                CartItem item = new CartItem();
                item.setProductId(productId);
                item.setProductPrice(productPrice);
                item.setColorName(colorName);
                // 获取一张图片作为样品图
                List list = productColorService.getProductImgs(productId, versionId, colorName);
                String url = (String) list.get(list.size() - 1);
                item.setProductImg(url);
                item.setQuantity(quantity);
                item.setVersionId(versionId);
                item.setProductName(productName);
                item.setProductTotalPrice(productPrice);
                modelMap.put("item", item);
                buyerCart.updateCartItemCount(item);
                cartService.addItemToCookie(buyerCart, response);
                return ServerResponse.createBySuccessMessage("更新成功");
            }
        } else {
            // 用户登陆了
            cartService.updateNewCount(productId, productName, productPrice, versionId, colorName, quantity, user.getUserEmail());
            // 取数据库中读取购物车
            List buyerCarts = cartService.selectCartItemByEmail(user.getUserEmail());
            modelMap.put("buyerCart", buyerCarts);
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMessage("更新失败");


    }

    /**
     * 选中一件商品，修改数据中的checked状态
     * @return
     */
    @RequestMapping("editChecked")
    @ResponseBody
    public ServerResponse editChecked( HttpServletRequest request, @RequestParam("productId") Integer productId, @RequestParam("productPrice") BigDecimal productPrice,
                                       @RequestParam("versionId") Integer versionId, @RequestParam("colorName") String colorName,
                                       @RequestParam("productName") String productName, @Param("checked") Integer checked) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user != null) {
            int resultCount = cartService.checked(productId, productName, productPrice, versionId, colorName, checked, user.getUserEmail());
            if (resultCount > 0) {
                return ServerResponse.createBySuccessMessage("更新成功");
            }
        }
        return ServerResponse.createByErrorMessage("更新失败");
    }


    @RequestMapping("order")
    public String pageJe() {
        return "my_order";
    }

}
